package com.xusiyan08.controller;

import com.xusiyan08.entity.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

@RestController
@RequestMapping("/api/feign-test")
public class FeignTestController {

    private final ItemFeignClient itemFeignClient;

    @Autowired
    public FeignTestController(ItemFeignClient itemFeignClient) {
        this.itemFeignClient = itemFeignClient;
    }

    @GetMapping("/item/{itemId}")
    public Mono<ResponseEntity<Item>> testGetItemById(@PathVariable Long itemId) {
        if (itemId != null && itemId == -1L) {
            // Explicitly cast the error to the expected Mono type to satisfy the compiler
            return Mono.<ResponseEntity<Item>>error(new RuntimeException("Simulated failure for itemId=-1 to test circuit breaker"))
                       .subscribeOn(Schedulers.boundedElastic());
        }
        // Simulate item not found by item-service for itemId == -2, but this won't trip CB by default
        // It's better to handle this by item-service returning 404, or specific logic in fallback if needed.
        // For now, we focus on -1 for tripping the circuit breaker.

        return Mono.fromCallable(() -> {
            // This call will be protected by the circuit breaker for 'cloud-second-hand'
            return itemFeignClient.getItemById(itemId);
        }).subscribeOn(Schedulers.boundedElastic());
    }
}
